<?php
require "./common/function.php";
require "./config/common.php";
//向数据库添加数据
if($_POST){
    $sql='';
//    编辑的参数
    $editType = $_REQUEST['editType'];
//    表单中的表数据
    $name = $_POST['productName'];
    $price = $_POST['productPrice'];
    $pnum = $_POST['productPnum'];
    $category = $_POST['category'];
    $description = $_POST['description'];

    $proId = $_REQUEST['proId'];

    //获取图片名字
    $fileName = basename($_FILES['imgUrl']['name']);
    $fileName1 = $_REQUEST['imgUrl1'];
    if(empty($fileName) && empty($fileName1)){
        $msg = [false,'请上传图片'];
        require './html/addProduct.html';
        exit;
    }

    if($fileName){
        $filePath = imgUrl.$fileName;
        if(!file_exists(imgUrl)){
            mkdir(imgUrl);
        }
        if(array_key_exists('imgUrl',$_FILES)){
            if(0==$_FILES['imgUrl']['error']){
                $gb = iconv('utf-8','gbk',$filePath);
//                如果文件重名，需要对文件名进行随机重命名
                $gb = renameFile($gb,$fileName);
                if(rename($_FILES['imgUrl']['tmp_name'],$gb)){
                    if($editType=='edit'){
                        $sql = "UPDATE t_product SET `name` = '$name',price = '$price',pnum = '$pnum',category = '$category',imgurl = '$fileName',description = '$description' WHERE id = '$proId'";
                    }else{
                        $sql="insert into `t_product`(`name`,`price`,`pnum`,`imgurl`,`category`,`description`) values ('$name','$price','$pnum','$fileName','$category','$description')";
                    }
                    $result = getMySql($sql,'操作数据失败');
                    display($result);
                }
            }
        }
    }else{
        if($editType=='edit'){
            $sql = "UPDATE t_product SET `name` = '$name',price = '$price',pnum = '$pnum',category = '$category',description = '$description' WHERE id = '$proId'";
        }
        $result = getMySql($sql,'操作数据失败');
        display($result);
    }
}

//查询商品分类信息
$sql="select * from t_category";
$result = getMySql($sql,'商品分类查询失败');
if($result){
    if(mysqli_num_rows($result)){
       $cates = mysqli_fetch_all($result,MYSQLI_ASSOC);
    }
}
//根据商品id查询商品信息
$prodId = $_REQUEST['id'];
if($prodId){
    $selSql="select * from t_product where id='$prodId'";
    $selResult = getMySql($selSql,'查询商品信息失败');
    if($selResult){
        if(mysqli_num_rows($selResult)){
            $selectResult = mysqli_fetch_array($selResult);
            $type="edit";
        }
    }
}
require "./html/addProduct.html";
exit;

function display($result){
    if($result){
        $msg=[true,"商品操作成功，返回商品管理"];
        $a = productUrl;
        require "./html/right.html";
        exit;
    }else{
        $msg=[false,"操作商品信息失败！"];
        require "./html/addProduct.html";
        exit;
    }
}

